var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp();
const {
  $Message
} = require('../../../dist/base/index');
Page({
  data: {
    addressList: [],
    defut: {},

    items: [],
    startX: 0, //开始坐标
    startY: 0,

    listnum: 10,


  },

  //返回上页
  back: function () {
    wx.navigateBack({})
  },


  getAddressList() {
    let that = this;
    var num = that.data.listnum;
    var url = 'current=1&size=' + num

    util.req(api.AddressList + url, {
      tokenType: 1
    }, "POST").then(function (res) {
      if (res.success) {
        var listSize = res.obj.records.length;
        console.log('listSize=' + listSize);
        var newData = that.data.addressList;
        newData = res.obj.records;
        var total1 = res.obj.total;
        var newList = {};
        //当长度小于10表示没有下页数据了
        if (listSize < num) {
          newList.hasMore = false;
        } else {
          newList.hasMore = true;
        }
        newList = newData;
        that.setData({
          addressList: newList,
          total: total1
        });

        if (newList.length == 1) {
          if (newList[0].isDefault == 0) {
            that.deft(0, newList[0].id)
          }
        }


        if (that.data.addressList.length == 0) {
          that.setData({
            defut: {}
          })
          wx.setStorageSync('defut', that.data.defut);
        } else {
          for (var i = 0; i < newList.length; i++) {
            if (newList[i].isDefault == 1) {
              console.log(newList[i])
              that.setData({
                defut: newList[i]
              })
              wx.setStorageSync('defut', that.data.defut);
            }
          }

        }
      }
    }).catch(function (res) {
      console.log("获取数据失败！")
    })

  },

  //修改地址的状态
  defStus: function (id, isDefault) {
    var that = this
    var data = {
      id: id,
      isDefault: isDefault
    }
    util.req(api.AddressDefult, data, "POST").then(function (res) {
      if (res.success) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        })
        that.onShow();
      } else {
        console.log("地址状态修改不成功")
      }
    }).catch(function (res) {
      console.log("获取数据失败！")
    })
  },

  //设置为默认地址
  deft: function (e, x) {
    let that = this;
    if (x !== undefined) {
      var Ids = x;
    } else {
      var Ids = e.currentTarget.id;
    }
    console.log("Ids=" + Ids)

    var list = that.data.addressList;
    var id = "";
    for (var i = 0; i < list.length; i++) {
      if (list[i].isDefault == 1) {
        id = list[i].id;
        console.log("id=" + id)
      }
    }
    if (id == "") {
      that.defStus(Ids, 1)
    } else {
      that.defStus(id, 0)
      that.defStus(Ids, 1)
    }


  },

  addressAdd(event) {
    console.log(event)
    wx.navigateTo({
      url: '/pages/ucenter/addressAdd/addressAdd'
    })
  },

  deleteAddress(event) {
    let that = this;
    wx.showModal({
      title: '',
      content: '确定删除该地址？',
      confirmColor: "#FF7D7C",
      success: function (res) {
        if (res.confirm) {
          let addressId = event.target.dataset.addressId;
          var url = JSON.stringify(addressId)
          console.log('url=' + url)
          util.req(api.AddressDelete + url, {}, "GET").then(function (res) {
            if (res.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              that.onShow();
            } else {
              console.log("地址状态修改不成功")
            }
          }).catch(function (res) {
            console.log("获取数据失败！")
          })
        }
      }
    })

  },

  updatead: function (e) {
    wx.navigateTo({
      url: '/pages/ucenter/address/adressinfo?id=' + e.currentTarget.id,
    })
  },


  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数

    var that = this;
    for (var i = 0; i < 10; i++) {
      this.data.items.push({
        content: i + " 向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦",
        isTouchMove: false //默认隐藏删除
      })
    }
    this.setData({
      items: this.data.items
    });
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.addressList.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      addressList: this.data.addressList
    })
  },

  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
          X: touchMoveX,
          Y: touchMoveY
        });
    that.data.addressList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })

    //更新数据
    that.setData({
      addressList: that.data.addressList
    })

  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */

  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件
  del: function (e) {
    this.data.addressList.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      addressList: this.data.addressList
    })
  },


  onReady: function () {
    // 页面渲染完成
  },

  onShow: function () {
    var that = this
    // 页面显示
    this.getAddressList();
    this.onLoad()


  },

  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})